package com.fly.demo.service.impl;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fly.common.exception.MyException;
import com.fly.common.util.Constant;
import com.fly.common.util.KeysUtil;
import com.fly.core.entity.JsonResult;
import com.fly.core.entity.PageRequest;
import com.fly.core.entity.PageResult;
import com.fly.core.entity.PageUtils;
import com.fly.demo.mapper.KcLoginDetailMapper;
import com.fly.demo.model.KcLoginDetail;
import com.fly.demo.service.LoginDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * 登录详情服务
 *
 * @author jack
 */
@Transactional
@Service
@Slf4j
public class LoginDetailServiceImpl implements LoginDetailService
{
    
    @Autowired
    private KcLoginDetailMapper kcLoginDetailMapper;
    
    @Override
    public JsonResult<?> loginRecord(String idNo, String courseTypId, String courseId)
    {
        try
        {
            LocalDateTime now = LocalDateTime.now();
            KcLoginDetail detail = KcLoginDetail.builder().id(KeysUtil.uuid()).idno(idNo).courseTypeId(courseTypId).courseId(courseId).loginTime(now.format(Constant.DT_FORMATTER)).createTime(now).delete(false).build();
            kcLoginDetailMapper.insert(detail);
            return JsonResult.success();
        }
        catch (Exception e)
        {
            log.error("登录记录插入异常", e);
        }
        return JsonResult.error("记录失败");
    }
    
    @Override
    public JsonResult<?> logoutRecord(String idNo, String courseTypId, String courseId)
    {
        try
        {
            KcLoginDetail login = kcLoginDetailMapper.selectByCondition(idNo, courseTypId, courseId);
            if (null == login)
            {
                return JsonResult.error("400", "没有对应的登录记录");
            }
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime loginTime = LocalDateTime.parse(login.getLoginTime(), Constant.DT_FORMATTER);
            Duration duration = Duration.between(loginTime, now);
            KcLoginDetail update = KcLoginDetail.builder().id(login.getId()).hours((int)(duration.toMillis() / 1000)).leaveTime(now.format(Constant.DT_FORMATTER)).updateTime(now).build();
            kcLoginDetailMapper.updateByPrimaryKeySelective(update);
            return JsonResult.success();
        }
        catch (Exception e)
        {
            log.error("退出登录记录更新异常", e);
        }
        return JsonResult.error("记录失败");
    }
    
    @Override
    public void batchInsert()
    {
        LocalDateTime now = LocalDateTime.now();
        Boolean fail = RandomUtils.nextBoolean();
        for (int i = 0; i < 10; i++)
        {
            KcLoginDetail detail = KcLoginDetail.builder().id(KeysUtil.uuid()).idno("1").courseTypeId("1").courseId("1").loginTime(now.format(Constant.DT_FORMATTER)).createTime(now).delete(false).build();
            kcLoginDetailMapper.insert(detail);
            
            // 构造自定义异常测试事务
            if (fail && i > 5 && RandomUtils.nextBoolean())
            {
                throw new MyException("自定义异常，i=" + i);
            }
        }
    }
    
    @Override
    public void deleteAll()
    {
        kcLoginDetailMapper.deleteAll();
    }
    
    @Override
    public PageResult findPage(PageRequest pageRequest)
    {
        return PageUtils.getPageResult(pageRequest, getPageInfo(pageRequest));
    }
    
    /**
     * 调用分页插件完成分页
     * 
     * @param pageQuery
     * @return
     */
    private PageInfo<KcLoginDetail> getPageInfo(PageRequest pageRequest)
    {
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<KcLoginDetail> details = kcLoginDetailMapper.selectPage();
        return new PageInfo(details);
    }
}
